import requests
import re
import pprint
from lxml import etree
import os

# 获取当前脚本的绝对路径
current_directory = os.path.dirname(os.path.abspath(__file__))
image_directory = os.path.join(current_directory, '图片')

# 拿到具体页面的链接下载一张图片
def download_images(url):
    rot = requests.get(url=url)
    rot.encoding = rot.apparent_encoding
    html = etree.HTML(rot.text)
    try:
        title = html.xpath('//div[@class="ImageBody"]//img/@alt')
        links = html.xpath('//div[@class="ImageBody"]//img/@src')
        number1 = html.xpath('//li[@class="thisclass"]/a[@href]/text()')  # 在这里提取 number1

        # 确保 title 和 number1 都有值
        if not title or not number1:
            print(f"未能提取标题或编号，URL: {url}")
            return

        # 创建文件夹
        image_folder = os.path.join(image_directory, title[0])
        if not os.path.exists(image_folder):
            os.makedirs(image_folder)  # 使用 makedirs 可以创建多层目录

        pic = requests.get(url=links[0]).content
        with open(os.path.join(image_folder, f'{title[0]}{str(number1[0])}.jpg'), 'wb') as f:
            f.write(pic)
            print(f'已下载……{title[0]}{str(number1[0])}')  # 提示下载成功
    except Exception as e:
        print(f'出错了......{url}, 错误信息: {e}')

# 给第一个图片的链接，就可以得到其他图片的链接
def link_of_pictures(url):
    rot = requests.get(url=url)
    rot.encoding = rot.apparent_encoding
    html = etree.HTML(rot.text)

    features = re.findall('xingganmeinv/(\\d+).htm', url)[0]

    # 获取页数
    numbers = html.xpath('//div[@class="NewPages"]//ul//li//a/text()')
    number = re.findall('共(\\d+)页', numbers[0])

    download_images(url)
    for i in range(2, int(number[0]) + 1):
        urll = re.sub(r'xingganmeinv/.*', f'xingganmeinv/{features}_{i}.htm', url)
        download_images(urll)

# 得到这个系列的单页的链接
url = 'https://www.umeituku.com/meinvtupian/'
header = {'user-agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/127.0.0.0 Safari/537.36 Edg/127.0.0.0'}
rt = requests.get(url=url, headers=header)
rt.encoding = rt.apparent_encoding
html = etree.HTML(rt.text)
title = html.xpath('//div[@class="TypeList"]//div[@class="ListTit"]/text()')
links = html.xpath('//div[@class="TypeList"]//a[@class="TypeBigPics"]/@href')

for item in links:
    link_of_pictures(str(item))
